#include "jr.h"
#include "widget.h"
#include<QDesktopWidget>
#include<QApplication>
#include<cstdlib>
#include<QMouseEvent>
#include<QPainter>

Jr::Jr(QWidget *parent) : QWidget(parent), jr(new QPixmap)
{
    //srand(time(nullptr)); 
    jr->load(":/img/jr_0.png");
    connect(this, &Jr::hit, (Widget*)parent, &Widget::get_score);    
    this->setFixedSize(this->jr->size()); 
    this->startTimer(100); 
}

void Jr::paintEvent(QPaintEvent *ev)
{
    QPainter p(this);
    p.drawPixmap(this->rect(), *jr); 
}


void Jr::timerEvent(QTimerEvent *ev)
{
   // this->index += 1; 
   // this->index %= 2; 
   // QString path = QString(":/img/jr_%1").arg(this->index); 
   // jr->load(path); 
    //srand(time(nullptr)); 

    #if 1
    int cur_x = this->geometry().topLeft().x() + rand() % 40 + 10;
    int cur_y = this->geometry().topLeft().y() + rand() % 40 + 10;
    QDesktopWidget *dest = QApplication::desktop(); 
    if(cur_x >= dest->geometry().right()) 
    {
        cur_x = dest->geometry().left(); 
        this->jr->load(":/img/jr_0.png"); 
    }
    if(cur_y >= dest->geometry().bottom()) 
    {
        cur_y = dest->geometry().top(); 
        this->jr->load(":/img/jr_0.png"); 
    }
    move(cur_x, cur_y); 
    update(); 
    #endif 
}

void Jr::mousePressEvent(QMouseEvent *event)
{
    this->offset = event->globalPos() - this->geometry().topLeft(); 
    this->jr->load(":/img/jr_1.png"); 
    emit hit(); 
    update(); 
}

#if 0
void Jr::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() & Qt::LeftButton)
        this->move(event->globaPos() - this->offset); 
}
#endif 